#! python3
# -*- coding: UTF-8 -*-
# @Time    : 2025/5/26 12:22
# @Author  : AndrewWay
# @version : 1.0
# @notes   ：

import requests
import json
from loguru import logger
from common.db import DB


class WeChatMonitor:
    def __init__(self, content):
        self.content = content
        self.logger = logger
        self.db: DB = DB()

    def start(self):
        """监控启动入口，触发消息发送"""
        self.edit_send_msg()

    # 编辑发送消息
    def edit_send_msg(self):
        """构造消息内容并执行发送"""
        msg = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"{self.content}"
            }
        }

        webhook = self.get_webhook()
        self._send_message(webhook, msg)

    def _send_message(self, webhook_url, message):
        """
        私有方法：实际执行消息发送
        :param webhook_url: 机器人webhook地址
        :param message: 消息内容字典
        """
        headers = {"Content-Type": "application/json"}
        try:
            response = requests.post(
                url=webhook_url,
                headers=headers,
                data=json.dumps(message)
            )
            response.raise_for_status()  # 检查HTTP状态码
            result = response.json()
            self.logger.info(f"消息发送成功")
            return result
        except requests.exceptions.ConnectionError:
            self.logger.error("错误：网络连接失败，请检查网络设置")
        except requests.exceptions.Timeout:
            self.logger.error("错误：请求超时，请检查网络连接或重试")
        except requests.exceptions.HTTPError as e:
            self.logger.error(f"错误：HTTP请求失败，状态码：{e.response.status_code}，响应内容：{e.response.text}")
        except Exception as e:
            self.logger.error(f"错误：发生未知异常：{str(e)}")
        return None

    def get_webhook(self):
        sql = f"select monitor_url from sys_conf where rebot_code = 'wechat_monitor'"
        result = self.db.query_one(sql)
        return result[0]


if __name__ == "__main__":
    # 使用示例
    WeChatMonitor("测试").start()
